function [AICs,AICcs,BICs] = laglength(Y,maxlag)

%Calculates AIC and BIC for VARs up to lag length maxlag
% Y is NxK matrix of observations

nv = size(Y,2);

lfy0 = ones(length(Y),1);

for i = 1:maxlag
    
      lfy0 = [lfy0 lagn(Y,i)];
    
end

    fy0v  = Y(maxlag+1:end,:);
    lfy0 = lfy0(maxlag+1:end,:);
    nobs = length(fy0v(:));
    
AICs = zeros(maxlag+1,1);    
AICcs = zeros(maxlag+1,1);
BICs = zeros(maxlag+1,1);

for k = 1:maxlag+1
        b0   = olss(fy0v,lfy0(:,1:nv*(k-1)+1));
        e0   = fy0v - lfy0(:,1:nv*(k-1)+1)*b0;
        np = length(b0(:))+1;
        
        BICs(k) =np*log(nobs)+nobs*log(sum(sum(e0.^2)));
        AICs(k) =np*2+nobs*log(sum(sum(e0.^2)));
        AICcs(k) = AICs(k) + np*(np+1)/(nobs-np-1);

end
